<?php

namespace app\admin\controller\order;

use app\admin\controller\goods\Goods;
use app\api\controller\WxPay;
use app\common\controller\Backend;
use app\common\library\Wxmini;
use app\common\model\UserCards;
use think\Controller;
use think\Db;
use think\Model;

/**
 * 售后单
 *
 * @icon fa fa-circle-o
 */
class Aftersales extends Backend
{

    /**
     * Aftersales模型对象
     * @var \app\common\model\order\Aftersales
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\order\Aftersales;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("aftersaleStatusList", $this->model->getAftersaleStatusList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign('checkinfoList',$this->model->checkinfoList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['order','user','item'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('order')->visible(['order_sn']);
				$row->getRelation('user')->visible(['nickname','mobile','avatar']);
				$row->getRelation('item')->visible(['goods_title','goods_image','goods_original_price','goods_price','goods_num','rights_title','rights_card','rights_tags','rights_num','used_num','canuse_num']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail()
    {
        if ($this->request->isPost()) {
            $id = input('post.ids');
            $status = input('post.checkinfo');
            $refund_fee = input('post.refund_fee');
            $before_checkinfo = input('before_checkinfo');
            $checkinfo = input('checkinfo', '');
            $refund_reason=input('refund_reason','');
            $row = $this->model->with('order')->find($id);
            if($row['refund_status']!=0&&$before_checkinfo!=$checkinfo){
                $this->error('售后已处理，无需处理');
            }
            if($row['refund_status']==0&&$before_checkinfo!=$checkinfo){
                if($checkinfo!=2&&!empty($refund_reason)){
                    $this->error('拒绝退款才需要填写退款拒绝理由');
                }
            }

            //  $row1 = $this->model->with('order')->find($id);
            $mitem=(new \app\common\model\order\OrderItem())->where(['id'=>$row['order_item_id']])->find();
            $total_price1= $mitem['goods_price']*$mitem['total_num'];

            Db::startTrans();
            $msg='';
            $msg1='';
            $order=(new \app\common\model\Order())->where(['id'=>$row['order_id']])->find();
            $checkinfoList=$this->model->checkinfoList;
            if ($before_checkinfo != $checkinfo) {

                $org = [
                    '订单状态由' . $checkinfoList[$before_checkinfo] . '改成' . $checkinfoList[$checkinfo],

                ];

                if($before_checkinfo==1||$before_checkinfo==2){
                    $this->error('无需重复审核');
                }
                switch ($checkinfo) {

                    case 1:

                        if( intval(strval($total_price1*100))<intval(strval($refund_fee*100))){
                            $this->error('退款金额超过本单最大退款金额');
                        }


                        //取消
                        //   $total_price=   (new \app\common\model\OrderItem())->where(['id'=>$row['order_item_id']])->value('')
                        $row['confirm_time'] =time();
                        $row['refund_fee'] = $refund_fee;
                        $row['refund_status']=1;
                        $row['aftersale_status']=2;
                        $row['confirm_time'] = time();
                        $row['refund_time']=time();
                        if($order['pay_type']=='wechat'){
                            $wx = new WxPay();
                            //  public function applyRefund($order_id, $refund_id, $to_back_fee, $refund_type = 'order', $reason = '')
                            $res = $wx->applyRefund($row['order_id'], $id,$refund_fee*100);
                            if(!$res['status']){
                                $this->error($res['msg']);
                            }
                        }

                        $time   =date('Y-m-d',$order['paytime']);
                        $item = (new \app\common\model\order\OrderItem())
                            ->where(['id'=>$row['order_item_id']])->find();

                        (new \app\admin\model\Goods())->where(['id'=>$item['goods_id']])->setDec('goods_sales');

                        UserCards::where(['order_id'=>$row['order_id']])->update(['status'=>3]);





                        (new \app\common\model\order\OrderItem())->where(['id'=>$row['order_item_id']])
                            ->update(['refund_status'=>2,'refund_fee'=>$refund_fee]);
                        break;
                    case 2:
                        //待支付
                        $row['refund_status']= -1;
                        $row['confirm_time'] =time();
                        $row['aftersale_status']=2;
                        (new UserCards())->where(['order_item_id'=>$row['order_item_id']])->update(['is_show'=>1]);
                         (new \app\common\model\order\OrderItem())->where(['id'=>$row['order_item_id']])
                            ->update(['refund_status'=>-1]);

                        (new \app\common\model\Order())->where(['id'=>$row['order_id']])->update(['refund_status'=>0]);
                        $msg='退款失败';
                        $org[] = '退款失败，理由：'.$refund_reason;
//                        $csave=['user_id'=>$row['user_id'],'order_id'=>$id,
//                            'admin_id'=>$this->auth->id,'type'=>6,
//                            'content'=>$refund_reason,'createtime'=>time()];
//                        db('refunse_reason')->insert($csave);
                        $msg1=empty($refund_reason)?'退款失败':$refund_reason;
                        break;


                }

                $res =$row->save();
            }else
            {
                $res =true;
            }

            if (isset($refund_fee) && $refund_fee != $row->refund_fee) {
                $org[] = '实际退款金额由' . $row->refund_fee . '改成' . $refund_fee;
            }
            $order = $this->model->with('order')->find($id);



            if (!empty($org)) {
                $this->modify_log($org, $row->id);
            }

            if($res){
                Db::commit();

                $count = (new \app\common\model\order\OrderItem())->where(['order_id'=>$row['order_id']])
                    ->where(['refund_status'=>2])->count();
                $count1= (new \app\common\model\order\OrderItem())
                    ->where(['order_id'=>$row['order_id']])->count();

                if($count==$count1){
                    \app\common\model\Order::where(['id'=>$row['order_id']])
                        ->update(['order_status'=>-2,'status'=>-2,'refund_status'=>2]);
                }else{
                    if($count>0){
                        \app\common\model\Order::where(['id'=>$row['order_id']])
                            ->update(['refund_status'=>1]);
                    }

                }


                $this->success('');
            }else{
                Db::rollback();
                $this->error('');
            }


            //   $orderrefund = db('order_refund')->where('id', $id)->find();

        }
        $param = $this->request->param();
        $row = $this->model->where(['id'=>$param['ids']])->find();
        $row->checkinfo =$this->getCheckinfo($row);
        $row['log']=\db('refundorder_log')->where(['order_id'=>$param['ids']])->select();
        //原订单商品
        $row->ordergoods = (new \app\common\model\order\OrderItem())->where('order_id', $row->order_id)->select();

        $pieces = explode(",", $row['images']);
        $row['imagess'] = $pieces;

        $row->order = model('order')->where('id', $row->order_id)->find();
        $this->view->assign('vo.order', $row->order);
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }
    public function getCheckinfo($row)
    {
        $checkinfo=0;
        if($row['refund_status']==-1){
            $checkinfo=2;
        } else if($row['refund_status']==1){
            $checkinfo=1;
        }
        return $checkinfo;
    }
    //修改日志记录
    public function modify_log($row,$order_id,$type='order'){

        $data = [
            'order_id'      =>  $order_id,
            'mod_content'   =>  implode('、',$row),
            'admin_id'      =>  session('admin.id'),
            'type'          =>  $type,
            'createtime'    =>  time(),
            'updatetime'    =>  time(),
        ];
        db('refundorder_log')->insert($data);

    }
}
